<template>
  <div class="all">
    <div class="left">
      <!-- 对应需求名称 + 负责人 - 可以废除需求/修改需求 -->
      <div class="outer" v-for="t in demand.info" :key="t._id">
        <div class="inner" @click="passinfo(t)">
          <div class="detail">
            {{ t.demand_name }}----{{ t.person_in_charge }}
            <div class="del" @click="del(t)">X</div>
          </div>
        </div>
      </div>
    </div>
    <div class="right" @click="isShow = true">
      <div class="inner" v-if="!isShow">
        <h3>点击左侧需求列表以修改需求或点击本侧空白处以添加需求</h3>
      </div>
      <div class="inner" v-if="isShow">
        <div class="realdiv" v-if="isChange">
          <h3>创建需求</h3>
          <label
            >需求名称&nbsp;&nbsp;&nbsp;&nbsp;:
            <el-input
              class="input_info"
              v-model="name"
              placeholder="请输入您要创建的需求名称"
              clearable
          /></label>

          <label
            >需求负责人:
            <el-input
              class="input_info"
              v-model="charge"
              placeholder="请输入该需求的负责人"
              clearable
          /></label>

          <label
            >完成天数&nbsp;&nbsp;&nbsp;&nbsp;:
            <el-input
              class="input_info"
              v-model="day"
              placeholder="请输入完成该需求所需要的天数"
              clearable
          /></label>

          <label
            >需求优先级&nbsp;&nbsp;&nbsp;&nbsp;:
            <el-input
              class="input_info"
              v-model="Level"
              placeholder="请输入您的需求名称"
              clearable
          /></label>

          <label
            >需求简介&nbsp;&nbsp;&nbsp;&nbsp;:
            <el-input
              class="input_info"
              v-model="detail"
              placeholder="请输入需求简介"
              clearable
          /></label>

          <el-row class="mb-4 outerbtn">
            <el-button class="btn" type="primary" @click="addDemand" round
              >完成创建</el-button
            >
          </el-row>
          <label v-if="tipx">
            <div class="tips">创建成功</div>
          </label>
        </div>

        <div class="realdiv" v-if="!isChange">
          <h3>修改需求(若某项无需修改则放置即可)</h3>
          <label
            >需求名称&nbsp;&nbsp;&nbsp;&nbsp;:
            <el-input
              class="input_info"
              v-model="name"
              placeholder="请输入您的需求名称(不超过9个字)"
              clearable
          /></label>

          <label
            >需求负责人:
            <el-input
              class="input_info"
              v-model="charge"
              placeholder="请输入该需求的负责人"
              clearable
          /></label>

          <label
            >完成天数&nbsp;&nbsp;&nbsp;&nbsp;:
            <el-input
              class="input_info"
              v-model="day"
              placeholder="请输入完成该需求所需要的天数"
              clearable
          /></label>

          <label
            >需求优先级&nbsp;&nbsp;&nbsp;&nbsp;:
            <el-input
              class="input_info"
              v-model="Level"
              placeholder="请输入您的需求优先级"
              clearable
          /></label>

          <label
            >需求简介&nbsp;&nbsp;&nbsp;&nbsp;:
            <el-input
              class="input_info"
              v-model="detail"
              placeholder="请输入需求简介(不超过100字)"
              clearable
          /></label>

          <el-row class="mb-4 outerbtn">
            <el-button class="btn" type="primary" @click="ChangeDemand" round
              >完成修改</el-button
            >
          </el-row>
          <label v-if="tip">
            <div class="tips">修改成功</div>
          </label>
          <div class="back" @click="isChange = true">添加需求</div>
        </div>
      </div>
    </div>
  </div>

  <div v-if="isDel" class="mask">
    <div class="dialog">
      <div>
        <h3>提示信息</h3>
        <h4>是否删除{{ name }}需求!!!</h4>
        <el-button class="btn_location" type="danger" @click="isDel = false"
          >取 消</el-button
        >
        <el-button type="info" @click="realDelete">确 定</el-button>
      </div>
    </div>
  </div>

  <div v-if="tips" class="mask">
    <div class="dialog">
      <div class="showtips">
        <div>您没有权限进行此操作!!</div>
        <el-button class="tipbtn" type="info" @click="checkright"
          >确 定</el-button
        >
      </div>
    </div>
  </div>
</template>

<script>
import { reactive, ref } from "@vue/reactivity";
import axios from "axios";
import { onMounted, onUnmounted } from "@vue/runtime-core";
import { nanoid } from "nanoid";
import { useStore } from "vuex";
import router from "../router/index.js";
export default {
  name: "Administration",
  setup() {
    let demand = reactive({
      info: [],
    });
    let name = ref("");
    let charge = ref("");
    let day = ref("");
    let detail = ref("");
    let ID = ref("");
    let Level = ref("");
    let isShow = ref(false);
    let isChange = ref(false);
    let isDel = ref(false);
    let tips = ref(false);
    // 建立一个收集信息的数组(修改前信息) 分别是需求名称、需求负责人、完成天数、需求优先级、需求简介 + 一个需求id
    let pre = reactive([]);
    // 建立一个关联store的参数
    let fornow = "";
    // 同样建立一个将修改的监听数组
    let willchange = [];
    let willchangeid = new Map();
    let willadd = [];
    let time;
    let timer;
    let tip = ref(false);
    let tipx = ref(false);
    let newDemandlength = ref(0);
    // ---
    const store = useStore();
    onMounted(() => {
      if (store.state.real_Item == "") {
        let data = JSON.parse(sessionStorage.getItem("cloud"));
        store.commit("useSessionStorage", [
          data.ItemID,
          data.DemandList,
          data.ItemList,
          data.main_person,
          data.real_Item,
          data.usernow,
          data.real_Demand,
        ]);
      }
      if (store.state.main_person !== store.state.usernow.name) {
        return (tips.value = true);
      }
      demand.info = store.state.real_Demand;

      time = setInterval(() => {
        if (willchange.length !== 0) {
          while (willchange.length !== 0) {
            // 2022-3-8修改的天数会出现问题,天数加上之后无法修改,但是有值
            axios({
              method: "post",
              url: "https://qcjk2s.api.cloudendpoint.cn/changeDemand",
              data: {
                name: willchange[0].demand_name,
                chargename: willchange[0].person_in_charge,
                day: willchange[0].ending_Time,
                detail: willchange[0].detailinfo,
                level: willchange[0].level,
                id: willchange[0].demand_ID,
              },
            }).then(
              (res) => {
                console.log("win");
              },
              (err) => {
                console.log(err.message);
              }
            );

            willchange.shift();
          }
        }
      }, 20000);

      timer = setInterval(() => {
        if (willadd.length !== 0) {
          while (willadd.length !== 0) {
            // 创建需求需要对项目ID+需求名称进行范围内排除筛选
            // 相当于要同时筛选出项目对应的需求信息,但是我知道我在那个项目！！！
            // 传参！项目ID
            axios({
              method: "post",
              url: "https://qcjk2s.api.cloudendpoint.cn/addDemand",
              data: {
                name: willadd[0].name,
                create_person: store.state.usernow.name,
                demand_ID: nanoid(),
                person_in_charge: willadd[0].charge,
                Item_ID: store.state.ItemID,
                day: willadd[0].day,
                detailinfo: willadd[0].detail,
                level: willadd[0].Level,
                main_person_id: store.state.usernow.id,
                userID: willadd[0].ID,
              },
            }).then(
              (res) => {
                console.log("win");
              },
              (err) => {
                console.log(err.message);
              }
            );
            willadd.shift();
          }
        }
      }, 60000);
    });

    onUnmounted(() => {
      if (willchange.length !== 0) {
        while (willchange.length !== 0) {
          axios({
            method: "post",
            url: "https://qcjk2s.api.cloudendpoint.cn/changeDemand",
            data: {
              name: willchange[0].demand_name,
              chargename: willchange[0].person_in_charge,
              day: willchange[0].ending_Time,
              detail: willchange[0].detailinfo,
              level: willchange[0].level,
              id: willchange[0].demand_ID,
            },
          }).then(
            (res) => {
              console.log("win");
            },
            (err) => {
              console.log(err.message);
            }
          );
          willchange.shift();
        }
      }
      if (willadd.length !== 0) {
        while (willadd.length !== 0) {
          // 创建需求需要对项目ID+需求名称进行范围内排除筛选
          // 相当于要同时筛选出项目对应的需求信息,但是我知道我在那个项目！！！
          // 传参！项目ID
          axios({
            method: "post",
            url: "https://qcjk2s.api.cloudendpoint.cn/addDemand",
            data: {
              name: willadd[0].name,
              create_person: store.state.usernow.name,
              demand_ID: willadd[0].demand_ID,
              person_in_charge: willadd[0].charge,
              Item_ID: store.state.ItemID,
              day: willadd[0].day,
              detailinfo: willadd[0].detail,
              level: willadd[0].Level,
              main_person_id: store.state.usernow.id,
              userID: willadd[0].ID,
            },
          }).then(
            (res) => {
              console.log("win");
            },
            (err) => {
              console.log(err.message);
            }
          );
          willadd.shift();
        }
      }
      clearInterval(time);
      clearInterval(timer);
    });

    function passinfo(t) {
      isShow.value = true;
      isChange.value = false;
      name.value = t.demand_name;
      Level.value = t.level;
      // console.log(t);
      pre[0] = t.demand_name;
      pre[1] = t.person_in_charge;
      pre[2] = t.ending_Time;
      pre[3] = t.level;
      pre[4] = t.detailinfo;
      fornow = t;
    }

    function ChangeDemand() {
      if (fornow.demand_ID == "") {
        alert("请重新登录后再进行修改");
      }
      if (name.value.length > 9 || detail.value.length > 100) {
        return alert("请限制需求名称和需求简介的字数!");
      }

      // 经过这里的操作vuex数据其实上和数据库中的数据已经同步 ---- 就不需要动态重新赋值vuex数据了
      name.value == "" ? _ : (fornow.demand_name = name.value);
      charge.value == "" ? _ : (fornow.person_in_charge = charge.value);
      Level.value == "" ? _ : (fornow.level = Level.value);
      day.value == "" ? _ : (fornow.ending_Time = day.value);
      detail.value == "" ? _ : (fornow.detailinfo = detail.value);

      //决定是否存放更新的数据
      if (
        (pre[0] != fornow.demand_name ||
          pre[1] != fornow.person_in_charge ||
          pre[3] != fornow.level ||
          per[2] != fornow.ending_Time ||
          per[4] != fornow.detailinfo) &&
        !willchangeid.has(fornow.demand_ID)
      ) {
        willchange.push(fornow);
        willchangeid.set(fornow.demand_ID, 1);
        // console.log(willchange);
      } else if (willchangeid.has(fornow.demand_ID)) {
        let c = 0;
        willchange.some((item, index) => {
          if (item.demand_ID === fornow.value.demand_ID) {
            c = index;
            return;
          }
        });
        willchange[c] = fornow;
        // console.log(willchange);
        tip.value = true;
        setTimeout(() => {
          tip.value = false;
        }, 2000);
      }
    }

    function addDemand() {
      if (name.value.length > 9 || detail.value.length > 100) {
        return alert("请限制需求名称和需求简介的字数!");
      }
      // 对需求名进行查重:
      for (let i = 0; i < store.state.real_Demand.length; i++) {
        if (store.state.real_Demand[i].demand_name == name.value) {
          return alert("已存在该需求");
        }
      }

      let userid = "";
      // 这里还是有点问题,后期改css样式时要限制只能添加小组成员，做成下拉选择的效果
      // 寻找给小组成员的小组成员id和负责人的id,用于传递需求的需求负责人id
      for (let i = 0; i < store.state.real_Item.member.length; i++) {
        // 寻找已有需求中的小组成员 我们应该找的是当前项目的小组成员,但是这样的话无法通过id查找,就会引发严重问题
        // 解决策略 => 项目组member数组内容改为:{姓名 ：...,id:...}
        if (store.state.real_Item.member[i].name == charge.value) {
          userid = store.state.real_Item.member[i].id;
        }
      }
      if (userid == "") {
        // console.log(store.state.usernow);
        if (store.state.usernow.name == charge.value) {
          userid = store.state.usernow.id;
        } else {
          return alert("该员工/负责人不存在!");
        }
      }
      let id = nanoid();
      let nowdata = {
        demand_name: name.value,
        person_in_charge: charge.value,
        ending_Time: day.value,
        level: Level.value,
        detailinfo: detail.value,
        demand_ID: id,
        createdAt: new Date(),
        updatedTime: "----",
        speed: 0,
        create_person: store.state.usernow.name,
      };
      store.commit("addRealDemand", nowdata);
      let data = {
        name: name.value,
        charge: charge.value,
        day: day.value,
        detail: detail.value,
        Level: Level.value,
        ID: userid,
        demand_ID: id,
      };
      willadd.push(data);
      tipx.value = true;
      // 清空输入框数据
      name.value = "";
      Level.value = "";
      charge.value = "";
      day.value = "";
      detail.value = "";
      setTimeout(() => {
        tipx.value = false;
      }, 2000);
    }

    function del(t) {
      // 删除进行数据重新获取
      isDel.value = true;
      ID = t;
    }

    function realDelete() {
      // 删除进行数据重新获取vuex
      isDel.value = false;
      let t = ID;
      axios({
        method: "post",
        url: "https://qcjk2s.api.cloudendpoint.cn/deleteDemand",
        data: {
          id: t.demand_ID,
        },
      }).then(
        (res) => {
          axios({
            method: "post",
            url: "https://qcjk2s.api.cloudendpoint.cn/hello",
            data: {
              name: store.state.usernow.username,
              password: store.state.usernow.password,
            },
          }).then(
            (res) => {
              // 更新vuex信息,直接重新获取
              let data = res.data;
              console.log("@", data);
              if (data === -1) return alert("用户名或密码错误");
              store.commit("UpdateState", [
                data.user[0],
                data.item,
                data.demand,
                data.user[0].lastItemID,
                1,
              ]);
              demand.info = store.state.real_Demand
              console.log(store.state);
            },
            (err) => {
              console.log(err.message);
            }
          );
        },
        (err) => {
          err.message;
        }
      );
    }

    function checkright() {
      router.push("/main/organizationInfo");
    }

    return {
      demand,
      isShow,
      isChange,
      name,
      charge,
      day,
      detail,
      tips,
      isDel,
      ID,
      Level,
      del,
      tip,
      tipx,
      ChangeDemand,
      passinfo,
      addDemand,
      checkright,
      realDelete,
    };
  },
};
</script>

<style lang="less" scoped>
.all {
  height: 100%;
  width: 100%;
  .left {
    width: 49.5%;
    height: 100%;
    float: left;
    border-bottom: 1px solid #ccc;
    border-right: 1px solid #ccc;
    overflow: auto;
    scrollbar-width: none;
    /* Firefox */
    -ms-overflow-style: none;
    border-bottom: 1px solid #ccc;
    .outer {
      height: 10%;
      width: 100%;
      overflow: auto;
      scrollbar-width: none;
      /* Firefox */
      -ms-overflow-style: none;
      border-bottom: 1px solid #ccc;
      .inner {
        height: 100%;
        width: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        position: relative;
        .del {
          position: absolute;
          top: 40%;
          right: 2%;
          color: #ccc;
          display: none;
        }
        &:hover {
          .del {
            display: block;
            cursor: pointer;
          }
        }
      }
    }
  }
  .right {
    width: 49.5%;
    height: 100%;
    float: left;
    display: flex;
    justify-content: center;
    align-items: center;
    .inner {
      width: 100%;
      h3 {
        margin-bottom: 5%;
        font-size: 18px;
        color: #409efc;
      }
      .realdiv {
        width: 100%;
        label {
          display: block;
          margin-bottom: 5%;
          .input_info {
            width: 50%;
          }
          .tips {
            margin: 3% 0 -3% 0;
            color: red;
          }
        }
      }
      .outerbtn {
        .btn {
          width: 200px;
          margin: 0 auto;
        }
      }
      .back {
        float: right;
        color: #409efc;
        cursor: pointer;
      }
    }
  }
}
.mask {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.5);

  .dialog {
    width: 300px;
    height: 300px;
    background-color: rgba(145, 145, 145, 0.5);
    text-align: center;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    div {
      h3 {
        margin: 20% 0 10% 0;
      }
      h4 {
        margin-bottom: 10%;
      }
      .btn_location {
        margin-right: 20%;
      }
    }
    .showtips {
      height: 100%;
      width: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      color: rgb(252, 110, 110);
      font-weight: bold;
      font-size: 20px;
      .tipbtn {
        margin-top: 10%;
      }
    }
  }
}
</style>